package com.yeskery.nut.web.demo.biz;

import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.bean.Component;
import com.yeskery.nut.extend.i18n.MessageService;
import com.yeskery.nut.web.demo.common.Log;
import com.yeskery.nut.web.demo.common.R;
import com.yeskery.nut.web.demo.common.UserContext;
import com.yeskery.nut.web.demo.domain.User;
import com.yeskery.nut.web.demo.domain.Wallet;
import com.yeskery.nut.web.demo.dto.UserDto;
import com.yeskery.nut.web.demo.exception.BusinessException;
import com.yeskery.nut.web.demo.service.UserService;
import com.yeskery.nut.web.demo.service.WalletService;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户biz
 * @author Yeskery
 * 2023/7/28
 */
@Component
public class UserBiz {

    @Autowired
    private UserService userService;

    @Autowired
    private WalletService walletService;

    @Autowired
    private MessageService messageService;

    /**
     * 获取所有用户列表
     * @return
     */
    @Log("获取所有用户列表")
    public List<UserDto> getUserList() {
        return userService.list().stream().map(u -> {
            UserDto userDto = new UserDto();
            userDto.setId(u.getId());
            userDto.setUsername(u.getUsername());
            userDto.setNickname(u.getNickname());
            return userDto;
        }).collect(Collectors.toList());
    }

    /**
     * 获取所有用户列表
     * @return
     */
    @Log("获取指定用户信息")
    public UserDto getUser(Integer id) {
        return userService.lambdaQuery()
                .eq(User::getId, id).oneOpt().map(u -> {
            UserDto userDto = new UserDto();
            userDto.setId(u.getId());
            userDto.setUsername(u.getUsername());
            userDto.setNickname(u.getNickname());
            return userDto;
        }).orElseThrow(() -> new BusinessException("用户不存在"));
    }

    /**
     * 查询当前登录的用户钱包信息
     * @return
     */
    @Log("获取当前登录的用户钱包信息")
    public R<Wallet> getCurrentUserWallet() {
        UserDto user = UserContext.getUser();
        Optional<Wallet> optional = walletService.lambdaQuery().eq(Wallet::getUserId, user.getId()).oneOpt();
        return optional.map(R::ok).orElseGet(() -> R.fail(messageService.getMessage("user.wallet.notfound")));
    }
}
